package com.xuecheng.system.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LoginDto;
import com.xuecheng.commons.model.vo.LoginVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.JwtUtils;
import com.xuecheng.system.domain.User;
import com.xuecheng.system.mappers.UserMapper;
import com.xuecheng.system.service.UserService;
import com.xuecheng.web.exceptions.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public ResponseResult login(LoginDto dto) {
        String phone = dto.getUsername();
        String password = dto.getPassword();
        String utype = dto.getUtype();
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(utype)||StringUtils.isEmpty(password)) {
//            throw new RuntimeException("账号密码为空！");
            throw new BusinessException(ErrorCode.LOGINERROR);
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,phone);
        queryWrapper.eq(User::getUtype,utype);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new BusinessException(ErrorCode.LOGINERROR);
        }
        password=DigestUtil.md5Hex(password);
        if (!password.equals(user.getPassword())){
            throw new RuntimeException("密码错误！");
        }
        Map map = new HashMap();
        map.put("userId",user.getId());
        map.put("companyId",user.getCompanyId());
        map.put("companyName",user.getCompanyName());
        String token = JwtUtils.createToken(map, 30);
        return ResponseResult.okResult(new LoginVo(token,user.getName()));
    }
}
